package org.zjt.rpc.util.watcher;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * Created by Administrator on 2017/3/14.
 */
public class ZkCuratorWatcher {
    private static String ZK_ADDR = "localhost:2181";

    private static String PARENT = "/super";

    public static void main(String[] args)throws Exception{
        RetryPolicy retryPolicy =new ExponentialBackoffRetry(10000 , 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(ZK_ADDR,retryPolicy);
        client.start();

        PathChildrenCache cache = new PathChildrenCache(client,PARENT,true);
        cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);

        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                switch (pathChildrenCacheEvent.getType()){
                    case CHILD_ADDED:
                        System.out.println(String.format("CHILD_ADDED  %s",pathChildrenCacheEvent.getData()));
                        break;
                    case CHILD_REMOVED:
                        System.out.println(String.format("CHILD_REMOVED  %s",pathChildrenCacheEvent.getData()));
                        break;
                    case CHILD_UPDATED:
                        System.out.println(String.format("CHILD_UPDATED  %s",pathChildrenCacheEvent.getData()));
                        break;
                    case CONNECTION_LOST:
                        System.out.println(String.format("CONNECTION_LOST  %s",pathChildrenCacheEvent.getData()));
                        break;
                    case INITIALIZED:
                        System.out.println(String.format("INITIALIZED  %s",pathChildrenCacheEvent.getData()));
                        break;
                    default:
                        System.out.println(String.format("default  %s",pathChildrenCacheEvent.getData()));
                        break;
                }
            }
        });

        Thread.sleep(1000);
        client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(PARENT+"/ZHANG","ZHANG".getBytes());
        Thread.sleep(1000);
        client.setData().forPath(PARENT+"/ZHANG","LI".getBytes());
        Thread.sleep(1000);
        client.delete().forPath(PARENT+"/ZHANG");
        Thread.sleep(1000);
        client.delete().deletingChildrenIfNeeded().forPath(PARENT);


        Thread.sleep(1000);
        client.close();
    }
}
